package com.example.shixun1.Fragment;

import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.shixun1.R;
import com.example.shixun1.activity.ProductDetailActivity;
import com.example.shixun1.adapter.ProductAdapter;
import com.example.shixun1.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MallFragment extends Fragment {
    private RecyclerView recyclerView;
    private ProductAdapter adapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mall, container, false);
        recyclerView = view.findViewById(R.id.rv_products);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));

        // 模拟数据
        List<Product> products = loadProducts();
        products.add(new Product("1", "苹果", "好吃的苹果", 4.00, R.drawable.product1));
        products.add(new Product("2", "大米", "高质的大米", 10.00, R.drawable.product2));

        adapter = new ProductAdapter(products, product -> {
            Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
            intent.putExtra("product", product);
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);
        return view;
    }
    private List<Product> loadProducts() {
        List<Product> products = new ArrayList<>();
        SharedPreferences prefs = getContext().getSharedPreferences("products", MODE_PRIVATE);

        Map<String, ?> allEntries = prefs.getAll();
        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            if (entry.getKey().endsWith("_name")) {
                String id = entry.getKey().replace("_name", "");
                String name = (String) entry.getValue();
                String description = prefs.getString(id + "_description", "");
                float price = prefs.getFloat(id + "_price", 0);
                String imageUri = prefs.getString(id + "_image", null);

                // 使用默认图片资源（实际项目应根据URI加载图片）
                products.add(new Product(id, name, description, price, R.drawable.product1));
            }
        }
        return products;
    }
}